<template>
  <div class="app-container">
    <!-- 搜索表单 -->
    <SearchForm
      v-model="searchForm"
      :inline="true"
      label-width="80px"
      @search="handleSearch"
      @reset="handleReset"
    >
      <el-form-item label="模板名称">
        <el-input v-model="searchForm.name" placeholder="请输入模板名称" clearable />
      </el-form-item>
      <el-form-item label="分类">
        <el-select v-model="searchForm.category" placeholder="请选择分类" clearable>
          <el-option 
            v-for="category in categories" 
            :key="category" 
            :label="category" 
            :value="category" 
          />
        </el-select>
      </el-form-item>
      <el-form-item label="状态">
        <el-select v-model="searchForm.status" placeholder="请选择状态" clearable>
          <el-option label="启用" value="ACTIVE" />
          <el-option label="禁用" value="INACTIVE" />
        </el-select>
      </el-form-item>
      <el-form-item label="创建时间">
        <el-date-picker
          v-model="searchForm.dateRange"
          type="daterange"
          range-separator="至"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          value-format="YYYY-MM-DD"
        />
      </el-form-item>
    </SearchForm>
    
    <!-- 统计卡片 -->
    <div class="stats-container">
      <StatCard
        title="模板总数"
        :value="statistics.totalTemplates || 0"
        icon="CollectionTag"
        type="primary"
      />
      <StatCard
        title="今日新增"
        :value="statistics.todayNewTemplates || 0"
        icon="Plus"
        type="success"
      />
      <StatCard
        title="总使用次数"
        :value="statistics.totalUsage || 0"
        icon="View"
        type="warning"
      />
      <StatCard
        title="热门模板"
        :value="statistics.hotTemplates || 0"
        icon="Fire"
        type="danger"
      />
    </div>
    
    <!-- 图表区域 -->
    <div class="chart-container">
      <div class="chart-row">
        <!-- 模板使用趋势 -->
        <div class="chart-card">
          <div class="chart-header">
            <div class="chart-title">模板使用趋势</div>
          </div>
          <div class="chart-content">
            <ChartContainer
              ref="usageTrendChartRef"
              :options="usageTrendChartOptions"
              :loading="chartLoading"
              height="300px"
            />
          </div>
        </div>
        
        <!-- 模板分类分布 -->
        <div class="chart-card">
          <div class="chart-header">
            <div class="chart-title">模板分类分布</div>
          </div>
          <div class="chart-content">
            <ChartContainer
              ref="categoryChartRef"
              :options="categoryChartOptions"
              :loading="chartLoading"
              height="300px"
            />
          </div>
        </div>
      </div>
    </div>
    
    <!-- 提示词模板表格 -->
    <Card title="提示词模板列表">
      <template #extra>
        <el-button type="primary" @click="handleAdd">
          <el-icon><Plus /></el-icon>
          新增模板
        </el-button>
        <el-button type="danger" @click="handleBatchDelete" :disabled="!selectedRows.length">
          <el-icon><Delete /></el-icon>
          批量删除
        </el-button>
        <el-button @click="handleExport">
          <el-icon><Download /></el-icon>
          导出
        </el-button>
      </template>
      
      <CommonTable
        ref="tableRef"
        :data="tableData"
        :columns="columns"
        :loading="loading"
        :pagination="pagination"
        @selection-change="handleSelectionChange"
        @sort-change="handleSortChange"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      >
        <template #status="{ row }">
          <el-tag :type="row.status === 'ACTIVE' ? 'success' : 'danger'">
            {{ row.status === 'ACTIVE' ? '启用' : '禁用' }}
          </el-tag>
        </template>
        
        <template #category="{ row }">
          <el-tag type="info">{{ row.category }}</el-tag>
        </template>
        
        <template #usageCount="{ row }">
          <el-badge :value="row.usageCount" :max="9999" type="primary" />
        </template>
        
        <template #action="{ row }">
          <el-button type="primary" link @click="handleView(row)">
            <el-icon><View /></el-icon>
            查看详情
          </el-button>
          <el-button type="primary" link @click="handleEdit(row)">
            <el-icon><Edit /></el-icon>
            编辑
          </el-button>
          <el-button type="primary" link @click="handleCopy(row)">
            <el-icon><CopyDocument /></el-icon>
            复制
          </el-button>
          <el-button type="primary" link @click="handleTest(row)">
            <el-icon><Check /></el-icon>
            测试
          </el-button>
          <el-button 
            type="primary" 
            link 
            @click="handleToggleStatus(row)"
          >
            <el-icon><Switch /></el-icon>
            {{ row.status === 'ACTIVE' ? '禁用' : '启用' }}
          </el-button>
          <el-button type="danger" link @click="handleDelete(row)">
            <el-icon><Delete /></el-icon>
            删除
          </el-button>
        </template>
      </CommonTable>
    </Card>
    
    <!-- 提示词模板表单对话框 -->
    <CommonDialog
      v-model="dialogVisible"
      :title="dialogType === 'add' ? '新增提示词模板' : '编辑提示词模板'"
      width="800px"
      @confirm="handleSubmit"
      @cancel="handleCancel"
    >
      <el-form
        ref="formRef"
        :model="formData"
        :rules="formRules"
        label-width="100px"
      >
        <el-form-item label="模板名称" prop="name">
          <el-input v-model="formData.name" placeholder="请输入模板名称" />
        </el-form-item>
        <el-form-item label="分类" prop="category">
          <el-select v-model="formData.category" placeholder="请选择分类" style="width: 100%">
            <el-option 
              v-for="category in categories" 
              :key="category" 
              :label="category" 
              :value="category" 
            />
            <el-option label="自定义" value="custom" />
          </el-select>
        </el-form-item>
        <el-form-item label="自定义分类" prop="customCategory" v-if="formData.category === 'custom'">
          <el-input v-model="formData.customCategory" placeholder="请输入自定义分类" />
        </el-form-item>
        <el-form-item label="标签" prop="tags">
          <el-select
            v-model="formData.tags"
            multiple
            filterable
            allow-create
            default-first-option
            placeholder="请选择或输入标签"
            style="width: 100%"
          >
            <el-option
              v-for="tag in tags"
              :key="tag"
              :label="tag"
              :value="tag"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="提示词" prop="prompt">
          <el-input 
            v-model="formData.prompt" 
            type="textarea" 
            placeholder="请输入提示词" 
            :rows="8" 
          />
        </el-form-item>
        <el-form-item label="描述" prop="description">
          <el-input 
            v-model="formData.description" 
            type="textarea" 
            placeholder="请输入描述" 
            :rows="4" 
          />
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-radio-group v-model="formData.status">
            <el-radio label="ACTIVE">启用</el-radio>
            <el-radio label="INACTIVE">禁用</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="排序" prop="sort">
          <el-input-number 
            v-model="formData.sort" 
            :min="0" 
            placeholder="请输入排序" 
          />
        </el-form-item>
      </el-form>
    </CommonDialog>
    
    <!-- 提示词模板详情对话框 -->
    <CommonDialog
      v-model="detailVisible"
      title="提示词模板详情"
      width="800px"
      :show-footer="false"
    >
      <el-descriptions :column="2" border>
        <el-descriptions-item label="模板名称">{{ detailData.name }}</el-descriptions-item>
        <el-descriptions-item label="分类">{{ detailData.category }}</el-descriptions-item>
        <el-descriptions-item label="状态">
          <el-tag :type="detailData.status === 'ACTIVE' ? 'success' : 'danger'">
            {{ detailData.status === 'ACTIVE' ? '启用' : '禁用' }}
          </el-tag>
        </el-descriptions-item>
        <el-descriptions-item label="使用次数">{{ detailData.usageCount }}</el-descriptions-item>
        <el-descriptions-item label="排序">{{ detailData.sort }}</el-descriptions-item>
        <el-descriptions-item label="创建时间">{{ detailData.createTime }}</el-descriptions-item>
        <el-descriptions-item label="更新时间">{{ detailData.updateTime }}</el-descriptions-item>
        <el-descriptions-item label="标签" :span="2">
          <el-tag v-for="tag in detailData.tags" :key="tag" style="margin-right: 5px;">
            {{ tag }}
          </el-tag>
        </el-descriptions-item>
      </el-descriptions>
      
      <div class="detail-content">
        <div class="content-header">
          <div class="content-title">提示词</div>
        </div>
        <div class="content-body prompt-content">
          {{ detailData.prompt }}
        </div>
      </div>
      
      <div class="detail-content">
        <div class="content-header">
          <div class="content-title">描述</div>
        </div>
        <div class="content-body">
          {{ detailData.description || '-' }}
        </div>
      </div>
    </CommonDialog>
    
    <!-- 测试对话框 -->
    <CommonDialog
      v-model="testVisible"
      title="测试提示词模板"
      width="800px"
      @confirm="handleTestSubmit"
      @cancel="handleCancelTest"
    >
      <el-form
        ref="testFormRef"
        :model="testForm"
        label-width="100px"
      >
        <el-form-item label="模板名称">
          <span>{{ currentTemplate.name }}</span>
        </el-form-item>
        <el-form-item label="模型类型" prop="modelType">
          <el-select v-model="testForm.modelType" placeholder="请选择模型类型" style="width: 100%">
            <el-option label="DeepSeek" value="DEEPSEEK" />
            <el-option label="Qwen" value="QWEN" />
            <el-option label="GLM" value="GLM" />
          </el-select>
        </el-form-item>
        <el-form-item label="输入内容" prop="input">
          <el-input 
            v-model="testForm.input" 
            type="textarea" 
            placeholder="请输入要测试的内容" 
            :rows="5" 
          />
        </el-form-item>
        <el-form-item label="温度" prop="temperature">
          <el-slider
            v-model="testForm.temperature"
            :min="0"
            :max="1"
            :step="0.1"
            :marks="{
              0: '0',
              0.5: '0.5',
              1: '1'
            }"
          />
        </el-form-item>
      </el-form>
      
      <div v-if="testResult.show" class="test-result">
        <div class="result-header">
          <span>测试结果</span>
        </div>
        
        <div class="result-content">
          <div class="result-item">
            <div class="result-label">输入内容：</div>
            <div class="result-value">{{ testResult.input }}</div>
          </div>
          <div class="result-item">
            <div class="result-label">输出内容：</div>
            <div class="result-value">{{ testResult.output }}</div>
          </div>
          <div class="result-item">
            <div class="result-label">使用令牌数：</div>
            <div class="result-value">{{ testResult.tokenCount }}</div>
          </div>
          <div class="result-item">
            <div class="result-label">响应时间：</div>
            <div class="result-value">{{ testResult.responseTime }}ms</div>
          </div>
        </div>
      </div>
    </CommonDialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { 
  getPromptTemplateList, 
  getPromptTemplateDetail, 
  createPromptTemplate, 
  updatePromptTemplate, 
  deletePromptTemplate, 
  batchDeletePromptTemplates, 
  updatePromptTemplateStatus, 
  getPromptTemplateUsageStatistics, 
  getPromptTemplateCategories, 
  getPromptTemplateTags,
  copyPromptTemplate,
  testPromptTemplate,
  getHotPromptTemplates
} from '@/api/promptTemplate'
import { useTable } from '@/hooks/useTable'
import { useForm } from '@/hooks/useForm'
import { useDialog } from '@/hooks/useDialog'

// 表格列配置
const columns = [
  {
    type: 'selection',
    width: '55'
  },
  {
    prop: 'id',
    label: 'ID',
    width: '80'
  },
  {
    prop: 'name',
    label: '模板名称',
    minWidth: '180'
  },
  {
    prop: 'category',
    label: '分类',
    width: '120',
    slot: 'category'
  },
  {
    prop: 'usageCount',
    label: '使用次数',
    width: '120',
    slot: 'usageCount'
  },
  {
    prop: 'status',
    label: '状态',
    width: '100',
    slot: 'status'
  },
  {
    prop: 'sort',
    label: '排序',
    width: '80'
  },
  {
    prop: 'createTime',
    label: '创建时间',
    width: '180',
    sortable: 'custom'
  },
  {
    prop: 'action',
    label: '操作',
    width: '350',
    slot: 'action',
    fixed: 'right'
  }
]

// 搜索表单
const searchForm = reactive({
  name: '',
  category: '',
  status: '',
  dateRange: []
})

// 统计数据
const statistics = reactive({
  totalTemplates: 0,
  todayNewTemplates: 0,
  totalUsage: 0,
  hotTemplates: 0
})

// 图表相关
const usageTrendChartRef = ref(null)
const categoryChartRef = ref(null)
const chartLoading = ref(false)
const usageTrendChartOptions = ref({})
const categoryChartOptions = ref({})

// 表格相关
const {
  tableData,
  loading,
  pagination,
  selectedRows,
  loadData,
  handleSelectionChange,
  handleSortChange,
  handleSizeChange,
  handleCurrentChange
} = useTable(getPromptTemplateList, {
  defaultParams: searchForm,
  immediate: false
})

// 表单相关
const defaultFormData = {
  name: '',
  category: '',
  customCategory: '',
  tags: [],
  prompt: '',
  description: '',
  status: 'ACTIVE',
  sort: 0
}

const formRules = {
  name: [
    { required: true, message: '请输入模板名称', trigger: 'blur' },
    { min: 1, max: 100, message: '模板名称长度在 1 到 100 个字符', trigger: 'blur' }
  ],
  category: [
    { required: true, message: '请选择分类', trigger: 'change' }
  ],
  customCategory: [
    { required: true, message: '请输入自定义分类', trigger: 'blur' }
  ],
  prompt: [
    { required: true, message: '请输入提示词', trigger: 'blur' }
  ],
  status: [
    { required: true, message: '请选择状态', trigger: 'change' }
  ]
}

const {
  formData,
  formRef,
  submitting,
  resetForm,
  validateForm,
  submitForm
} = useForm(defaultFormData, handleSubmit, {
  resetAfterSubmit: false
})

// 测试表单相关
const {
  formData: testForm,
  formRef: testFormRef
} = useForm({
  modelType: 'DEEPSEEK',
  input: '',
  temperature: 0.7
})

// 对话框相关
const {
  visible: dialogVisible,
  showDialog,
  hideDialog
} = useDialog()

const {
  visible: detailVisible,
  showDialog: showDetailDialog,
  hideDialog: hideDetailDialog
} = useDialog()

const {
  visible: testVisible,
  showDialog: showTestDialog,
  hideDialog: hideTestDialog
} = useDialog()

// 其他变量
const tableRef = ref(null)
const dialogType = ref('add')
const categories = ref([])
const tags = ref([])
const detailData = reactive({})
const currentTemplate = reactive({})
const testResult = reactive({
  show: false,
  input: '',
  output: '',
  tokenCount: 0,
  responseTime: 0
})

// 获取统计数据
const getStatisticsData = async () => {
  try {
    const response = await getPromptTemplateUsageStatistics()
    if (response) {
      Object.assign(statistics, response)
    }
  } catch (error) {
    console.error('获取统计数据失败', error)
  }
}

// 获取提示词模板分类列表
const getCategoriesData = async () => {
  try {
    const response = await getPromptTemplateCategories()
    if (response && response.data) {
      categories.value = response.data
    }
  } catch (error) {
    console.error('获取提示词模板分类列表失败', error)
  }
}

// 获取提示词模板标签列表
const getTagsData = async () => {
  try {
    const response = await getPromptTemplateTags()
    if (response && response.data) {
      tags.value = response.data
    }
  } catch (error) {
    console.error('获取提示词模板标签列表失败', error)
  }
}

// 获取图表数据
const getChartData = async () => {
  try {
    chartLoading.value = true
    
    // 模拟获取模板使用趋势数据
    const usageTrendData = {
      xAxis: {
        type: 'category',
        data: ['周一', '周二', '周三', '周四', '周五', '周六', '周日']
      },
      yAxis: {
        type: 'value'
      },
      series: [
        {
          name: '使用次数',
          type: 'line',
          smooth: true,
          data: [120, 132, 101, 134, 90, 230, 210],
          areaStyle: {
            color: 'rgba(24, 144, 255, 0.2)'
          },
          lineStyle: {
            color: '#1890ff'
          }
        }
      ]
    }
    
    // 模拟获取模板分类分布数据
    const categoryData = {
      tooltip: {
        trigger: 'item',
        formatter: '{a} <br/>{b}: {c} ({d}%)'
      },
      legend: {
        orient: 'vertical',
        left: 'left'
      },
      series: [
        {
          name: '模板分类分布',
          type: 'pie',
          radius: '50%',
          data: [
            { value: 335, name: '写作助手' },
            { value: 310, name: '代码助手' },
            { value: 234, name: '翻译助手' },
            { value: 135, name: '学习助手' },
            { value: 154, name: '其他' }
          ],
          emphasis: {
            itemStyle: {
              shadowBlur: 10,
              shadowOffsetX: 0,
              shadowColor: 'rgba(0, 0, 0, 0.5)'
            }
          }
        }
      ]
    }
    
    usageTrendChartOptions.value = usageTrendData
    categoryChartOptions.value = categoryData
  } catch (error) {
    console.error('获取图表数据失败', error)
  } finally {
    chartLoading.value = false
  }
}

// 处理搜索
const handleSearch = () => {
  loadData({
    ...searchForm,
    startTime: searchForm.dateRange?.[0],
    endTime: searchForm.dateRange?.[1]
  })
}

// 处理重置
const handleReset = () => {
  Object.assign(searchForm, {
    name: '',
    category: '',
    status: '',
    dateRange: []
  })
  handleSearch()
}

// 处理新增
const handleAdd = () => {
  dialogType.value = 'add'
  resetForm()
  showDialog()
}

// 处理编辑
const handleEdit = async (row) => {
  try {
    const response = await getPromptTemplateDetail(row.id)
    if (response) {
      dialogType.value = 'edit'
      Object.assign(formData, response)
      showDialog()
    }
  } catch (error) {
    console.error('获取提示词模板详情失败', error)
  }
}

// 处理查看
const handleView = async (row) => {
  try {
    const response = await getPromptTemplateDetail(row.id)
    if (response) {
      Object.assign(detailData, response)
      showDetailDialog()
    }
  } catch (error) {
    console.error('获取提示词模板详情失败', error)
  }
}

// 处理复制
const handleCopy = async (row) => {
  try {
    const response = await copyPromptTemplate(row.id)
    if (response) {
      ElMessage.success('复制成功')
      loadData()
      getStatisticsData()
    }
  } catch (error) {
    console.error('复制失败', error)
  }
}

// 处理测试
const handleTest = (row) => {
  Object.assign(currentTemplate, row)
  testForm.modelType = 'DEEPSEEK'
  testForm.input = ''
  testForm.temperature = 0.7
  testResult.show = false
  testResult.input = ''
  testResult.output = ''
  testResult.tokenCount = 0
  testResult.responseTime = 0
  showTestDialog()
}

// 处理测试提交
const handleTestSubmit = async () => {
  if (!testForm.input) {
    ElMessage.warning('请输入要测试的内容')
    return
  }
  
  try {
    const response = await testPromptTemplate(currentTemplate.id, testForm)
    
    if (response) {
      testResult.show = true
      testResult.input = testForm.input
      testResult.output = response.output || ''
      testResult.tokenCount = response.tokenCount || 0
      testResult.responseTime = response.responseTime || 0
    }
  } catch (error) {
    console.error('测试失败', error)
  }
}

// 处理取消测试
const handleCancelTest = () => {
  hideTestDialog()
}

// 处理删除
const handleDelete = (row) => {
  ElMessageBox.confirm(
    `确定要删除提示词模板 "${row.name}" 吗？`,
    '提示',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }
  ).then(async () => {
    try {
      await deletePromptTemplate(row.id)
      ElMessage.success('删除成功')
      loadData()
      getStatisticsData()
    } catch (error) {
      console.error('删除失败', error)
    }
  }).catch(() => {})
}

// 处理批量删除
const handleBatchDelete = () => {
  if (!selectedRows.value.length) {
    ElMessage.warning('请选择要删除的提示词模板')
    return
  }
  
  const ids = selectedRows.value.map(row => row.id)
  
  ElMessageBox.confirm(
    `确定要删除选中的 ${ids.length} 个提示词模板吗？`,
    '提示',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }
  ).then(async () => {
    try {
      await batchDeletePromptTemplates(ids)
      ElMessage.success('批量删除成功')
      loadData()
      getStatisticsData()
    } catch (error) {
      console.error('批量删除失败', error)
    }
  }).catch(() => {})
}

// 处理切换状态
const handleToggleStatus = (row) => {
  const newStatus = row.status === 'ACTIVE' ? 'INACTIVE' : 'ACTIVE'
  const statusText = newStatus === 'ACTIVE' ? '启用' : '禁用'
  
  ElMessageBox.confirm(
    `确定要${statusText}提示词模板 "${row.name}" 吗？`,
    '提示',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }
  ).then(async () => {
    try {
      await updatePromptTemplateStatus(row.id, newStatus)
      ElMessage.success(`${statusText}成功`)
      loadData()
      getStatisticsData()
    } catch (error) {
      console.error(`${statusText}失败`, error)
    }
  }).catch(() => {})
}

// 处理导出
const handleExport = () => {
  ElMessage.info('导出功能开发中')
}

// 处理表单提交
async function handleSubmit() {
  try {
    const category = formData.category === 'custom' ? formData.customCategory : formData.category
    
    const data = {
      ...formData,
      category
    }
    
    if (dialogType.value === 'add') {
      await createPromptTemplate(data)
      ElMessage.success('新增成功')
    } else {
      await updatePromptTemplate(formData.id, data)
      ElMessage.success('更新成功')
    }
    
    hideDialog()
    loadData()
    getStatisticsData()
  } catch (error) {
    console.error('提交失败', error)
  }
}

// 处理取消
const handleCancel = () => {
  hideDialog()
}

onMounted(() => {
  loadData()
  getStatisticsData()
  getCategoriesData()
  getTagsData()
  getChartData()
})
</script>

<style lang="scss" scoped>
.app-container {
  .stats-container {
    display: grid;
    grid-template-columns: repeat(auto-fill, minmax(250px, 1fr));
    gap: 20px;
    margin-bottom: 20px;
  }
  
  .chart-container {
    margin-bottom: 20px;
    
    .chart-row {
      display: grid;
      grid-template-columns: repeat(auto-fit, minmax(500px, 1fr));
      gap: 20px;
      
      .chart-card {
        background: var(--el-bg-color-overlay);
        border-radius: var(--el-border-radius-base);
        box-shadow: var(--el-box-shadow-lighter);
        padding: 20px;
        
        .chart-header {
          display: flex;
          justify-content: space-between;
          align-items: center;
          margin-bottom: 16px;
          
          .chart-title {
            font-size: 16px;
            font-weight: bold;
            color: var(--el-text-color-primary);
          }
        }
        
        .chart-content {
          height: 300px;
        }
      }
    }
  }
  
  .detail-content {
    margin-top: 20px;
    
    .content-header {
      margin-bottom: 12px;
      
      .content-title {
        font-size: 16px;
        font-weight: bold;
        color: var(--el-text-color-primary);
      }
    }
    
    .content-body {
      padding: 16px;
      border-radius: var(--el-border-radius-base);
      background-color: var(--el-fill-color-lighter);
      white-space: pre-wrap;
      line-height: 1.6;
      
      &.prompt-content {
        font-family: monospace;
        background-color: var(--el-fill-color-darker);
        color: var(--el-color-white);
      }
    }
  }
  
  .test-result {
    margin-top: 20px;
    padding: 16px;
    border-radius: var(--el-border-radius-base);
    background-color: var(--el-fill-color-lighter);
    
    .result-header {
      margin-bottom: 16px;
      
      span {
        font-size: 16px;
        font-weight: bold;
        color: var(--el-text-color-primary);
      }
    }
    
    .result-content {
      .result-item {
        margin-bottom: 12px;
        
        .result-label {
          font-size: 14px;
          color: var(--el-text-color-regular);
          margin-bottom: 4px;
        }
        
        .result-value {
          font-size: 14px;
          color: var(--el-text-color-primary);
          word-break: break-word;
          white-space: pre-wrap;
          line-height: 1.6;
        }
      }
    }
  }
}
</style>